use security_lib::{
    HttpRequestInfo, InputType, SecurityConfig, SecurityGuard, SecurityRuleType, SecuritySeverity,
};
use std::collections::HashMap;

fn main() {
    println!("=== HTTP 安全防护库使用示例 ===\n");

    // 1. 创建安全守卫实例
    let mut security_guard = SecurityGuard::new_with_default();

    // 2. 或者使用自定义配置
    let custom_config = SecurityConfig {
        enable_path_traversal_check: true,
        enable_xss_check: true,
        enable_sql_injection_check: true,
        enable_csrf_check: true,
        enable_rate_limit: true,
        allowed_file_extensions: vec!["jpg".to_string(), "png".to_string(), "pdf".to_string()],
        max_request_size: 5_000_000, // 5MB
        csrf_token_name: "csrf_token".to_string(),
        rate_limit_requests: 50,
        rate_limit_window_seconds: 3600,
    };
    let _custom_guard = SecurityGuard::new(custom_config);

    // 3. 测试正常请求
    println!("--- 测试正常请求 ---");
    let normal_request = create_normal_request();
    let result = security_guard.check_request(&normal_request);
    println!(
        "正常请求检查结果: {}",
        if result.is_safe {
            "安全"
        } else {
            "不安全"
        }
    );
    print_violations(&result.violations);

    // 4. 测试路径越权攻击
    println!("\n--- 测试路径越权攻击 ---");
    let path_traversal_request = create_path_traversal_request();
    let result = security_guard.check_request(&path_traversal_request);
    println!(
        "路径越权攻击检查结果: {}",
        if result.is_safe {
            "安全"
        } else {
            "检测到攻击"
        }
    );
    print_violations(&result.violations);

    // 5. 测试XSS攻击
    println!("\n--- 测试XSS攻击 ---");
    let xss_request = create_xss_request();
    let result = security_guard.check_request(&xss_request);
    println!(
        "XSS攻击检查结果: {}",
        if result.is_safe {
            "安全"
        } else {
            "检测到攻击"
        }
    );
    print_violations(&result.violations);

    // 6. 测试SQL注入攻击
    println!("\n--- 测试SQL注入攻击 ---");
    let sql_injection_request = create_sql_injection_request();
    let result = security_guard.check_request(&sql_injection_request);
    println!(
        "SQL注入攻击检查结果: {}",
        if result.is_safe {
            "安全"
        } else {
            "检测到攻击"
        }
    );
    print_violations(&result.violations);

    // 7. 测试CSRF攻击
    println!("\n--- 测试CSRF攻击 ---");
    let csrf_request = create_csrf_request();
    let result = security_guard.check_request(&csrf_request);
    println!(
        "CSRF攻击检查结果: {}",
        if result.is_safe {
            "安全"
        } else {
            "检测到攻击"
        }
    );
    print_violations(&result.violations);

    // 8. 测试加密解密功能
    println!("\n--- 测试加密解密功能 ---");
    test_encryption(&security_guard);

    // 9. 测试CSRF Token生成和验证
    println!("\n--- 测试CSRF Token ---");
    test_csrf_token(&mut security_guard);

    // 10. 测试密码强度检查
    println!("\n--- 测试密码强度检查 ---");
    test_password_strength(&security_guard);

    // 11. 测试频率限制
    println!("\n--- 测试频率限制 ---");
    test_rate_limit(&mut security_guard);

    // 12. 测试输入验证功能
    println!("\n--- 测试输入验证功能 ---");
    test_input_validation(&security_guard);

    // 13. 测试安全响应头生成
    println!("\n--- 测试安全响应头生成 ---");
    test_security_headers(&security_guard);

    // 14. 测试增强的CSRF保护
    println!("\n--- 测试增强的CSRF保护 ---");
    test_enhanced_csrf(&mut security_guard);
}

fn create_normal_request() -> HttpRequestInfo {
    let mut headers = HashMap::new();
    headers.insert("content-type".to_string(), "application/json".to_string());
    headers.insert("authorization".to_string(), "Bearer token123".to_string());

    let mut query_params = HashMap::new();
    query_params.insert("page".to_string(), "1".to_string());
    query_params.insert("size".to_string(), "10".to_string());

    HttpRequestInfo {
        method: "GET".to_string(),
        url: "https://api.example.com/users".to_string(),
        headers,
        body: None,
        query_params,
        form_data: HashMap::new(),
        cookies: HashMap::new(),
        client_ip: "192.168.1.100".to_string(),
        user_agent: Some(
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
        ),
        referer: Some("https://example.com".to_string()),
    }
}

fn create_path_traversal_request() -> HttpRequestInfo {
    let mut query_params = HashMap::new();
    query_params.insert("file".to_string(), "../../../etc/passwd".to_string());
    query_params.insert(
        "path".to_string(),
        "..\\..\\windows\\system32\\config\\sam".to_string(),
    );

    HttpRequestInfo {
        method: "GET".to_string(),
        url: "https://api.example.com/download?file=../../../etc/passwd".to_string(),
        headers: HashMap::new(),
        body: None,
        query_params,
        form_data: HashMap::new(),
        cookies: HashMap::new(),
        client_ip: "192.168.1.100".to_string(),
        user_agent: Some("Mozilla/5.0".to_string()),
        referer: Some("https://example.com".to_string()),
    }
}

fn create_xss_request() -> HttpRequestInfo {
    let mut form_data = HashMap::new();
    form_data.insert(
        "comment".to_string(),
        "<script>alert('XSS Attack!')</script>".to_string(),
    );
    form_data.insert(
        "username".to_string(),
        "<img src=x onerror=alert('XSS')>".to_string(),
    );

    let body = Some(r#"{"content": "<iframe src=javascript:alert('XSS')></iframe>"}"#.to_string());

    HttpRequestInfo {
        method: "POST".to_string(),
        url: "https://api.example.com/comments".to_string(),
        headers: HashMap::new(),
        body,
        query_params: HashMap::new(),
        form_data,
        cookies: HashMap::new(),
        client_ip: "192.168.1.100".to_string(),
        user_agent: Some("Mozilla/5.0".to_string()),
        referer: Some("https://example.com".to_string()),
    }
}

fn create_sql_injection_request() -> HttpRequestInfo {
    let mut query_params = HashMap::new();
    query_params.insert("id".to_string(), "1 OR 1=1--".to_string());
    query_params.insert(
        "username".to_string(),
        "admin'; DROP TABLE users; --".to_string(),
    );

    let mut form_data = HashMap::new();
    form_data.insert(
        "search".to_string(),
        "test' UNION SELECT * FROM passwords--".to_string(),
    );

    HttpRequestInfo {
        method: "POST".to_string(),
        url: "https://api.example.com/search?id=1 OR 1=1--".to_string(),
        headers: HashMap::new(),
        body: Some(r#"{"query": "SELECT * FROM users WHERE id = '1' OR '1'='1'"}"#.to_string()),
        query_params,
        form_data,
        cookies: HashMap::new(),
        client_ip: "192.168.1.100".to_string(),
        user_agent: Some("Mozilla/5.0".to_string()),
        referer: Some("https://example.com".to_string()),
    }
}

fn create_csrf_request() -> HttpRequestInfo {
    let mut form_data = HashMap::new();
    form_data.insert("amount".to_string(), "1000".to_string());
    form_data.insert("to_account".to_string(), "attacker_account".to_string());
    // 注意：这里故意不包含CSRF token

    HttpRequestInfo {
        method: "POST".to_string(),
        url: "https://bank.example.com/transfer".to_string(),
        headers: HashMap::new(),
        body: None,
        query_params: HashMap::new(),
        form_data,
        cookies: HashMap::new(),
        client_ip: "192.168.1.100".to_string(),
        user_agent: Some("Mozilla/5.0".to_string()),
        referer: Some("https://evil-site.com".to_string()), // 可疑的referer
    }
}

fn test_encryption(guard: &SecurityGuard) {
    let key = "my_super_secret_key_2024";
    let plaintext = "这是需要加密的敏感数据：用户ID=12345, 余额=50000.00";

    println!("原始数据: {}", plaintext);

    // 测试AES加密
    match guard.encrypt_aes256(key, plaintext) {
        Ok(encrypted) => {
            println!("AES-256-GCM加密结果: {}", encrypted);

            // 测试解密
            match guard.decrypt_aes256(key, &encrypted) {
                Ok(decrypted) => {
                    println!("AES-256-GCM解密结果: {}", decrypted);
                    println!("解密是否成功: {}", plaintext == decrypted);
                }
                Err(e) => println!("解密失败: {}", e),
            }
        }
        Err(e) => println!("加密失败: {}", e),
    }

    // 测试SHA256哈希
    let hash = guard.hash_sha256(plaintext);
    println!("SHA256哈希: {}", hash);

    // 测试HMAC
    if let Ok(hmac) = guard.hmac_sha256(key, plaintext) {
        println!("HMAC-SHA256: {}", hmac);
    }

    // 生成随机密码
    let random_password = guard.generate_random_password(16);
    println!("生成的随机密码: {}", random_password);
}

fn test_csrf_token(guard: &mut SecurityGuard) {
    let session_id = "user_session_12345";

    // 生成CSRF token
    let token = guard.generate_csrf_token(session_id);
    println!("生成的CSRF Token: {}", token);

    // 验证token
    let is_valid = guard.verify_csrf_token(&token, session_id);
    println!("Token验证结果: {}", if is_valid { "有效" } else { "无效" });

    // 测试错误的session_id
    let is_invalid = guard.verify_csrf_token(&token, "wrong_session");
    println!(
        "错误session验证结果: {}",
        if is_invalid { "有效" } else { "无效" }
    );
}

fn test_password_strength(guard: &SecurityGuard) {
    let passwords = vec![
        "123",
        "password",
        "Password123",
        "MyStr0ng!Pass",
        "Sup3r$3cur3P@ssw0rd!",
    ];

    for password in passwords {
        let strength = guard.check_password_strength(password);
        println!(
            "密码: {} => 强度: {:?}, 得分: {}/5",
            password, strength.level, strength.score
        );
        if !strength.issues.is_empty() {
            println!("  改进建议: {}", strength.issues.join(", "));
        }
    }
}

fn test_rate_limit(guard: &mut SecurityGuard) {
    let request = create_normal_request();

    println!("模拟同一IP的多次请求...");
    for i in 1..=5 {
        let result = guard.check_request(&request);
        println!(
            "第{}次请求: {}",
            i,
            if result.is_safe {
                "通过"
            } else {
                "被拦截"
            }
        );

        if !result.is_safe {
            for violation in &result.violations {
                if matches!(violation.rule_type, SecurityRuleType::RateLimit) {
                    println!("  拦截原因: {}", violation.message);
                }
            }
        }
    }
}

fn test_input_validation(guard: &SecurityGuard) {
    let test_cases = vec![
        ("test@example.com", InputType::Email),
        ("invalid-email", InputType::Email),
        ("https://example.com", InputType::Url),
        ("javascript:alert('xss')", InputType::Url),
        ("+1234567890", InputType::Phone),
        ("abc123", InputType::Phone),
        ("valid_username", InputType::Username),
        ("user@name", InputType::Username),
        ("StrongPass123!", InputType::Password),
        ("123", InputType::Password),
        ("123.45", InputType::Numeric),
        ("abc123", InputType::Numeric),
        ("ABC123", InputType::Alphanumeric),
        ("ABC-123", InputType::Alphanumeric),
        ("Normal text", InputType::Text),
        ("<script>alert('xss')</script>", InputType::Html),
    ];

    for (input, input_type) in test_cases {
        match guard.validate_and_filter_input(input, input_type.clone()) {
            Ok(result) => {
                println!(
                    "✅ {}: '{}' -> '{}'",
                    format!("{:?}", input_type),
                    input,
                    result
                );
            }
            Err(e) => {
                println!(
                    "❌ {}: '{}' -> 错误: {}",
                    format!("{:?}", input_type),
                    input,
                    e
                );
            }
        }
    }
}

fn test_security_headers(guard: &SecurityGuard) {
    println!("生成的安全响应头:");
    let headers = guard.generate_security_headers(Some("example.com"));

    for (key, value) in headers {
        println!("  {}: {}", key, value);
    }

    println!("\n生成的安全响应头 (无域名):");
    let headers_no_domain = guard.generate_security_headers(None);

    for (key, value) in headers_no_domain {
        println!("  {}: {}", key, value);
    }
}

fn test_enhanced_csrf(guard: &mut SecurityGuard) {
    // 测试双重提交CSRF Token
    let session_id = "user_session_67890";
    let (form_token, cookie_token) = guard.generate_double_submit_csrf_token(session_id);

    println!("生成的双重提交CSRF Token:");
    println!("  Form Token: {}", form_token);
    println!("  Cookie Token: {}", cookie_token);

    // 验证正确的token
    let is_valid = guard.verify_double_submit_csrf_token(&form_token, &cookie_token);
    println!("Token验证结果: {}", if is_valid { "有效" } else { "无效" });

    // 验证错误的token
    let is_invalid = guard.verify_double_submit_csrf_token(&form_token, "wrong_token");
    println!(
        "错误Token验证结果: {}",
        if is_invalid { "有效" } else { "无效" }
    );

    // 测试增强的CSRF检查
    let mut csrf_request = create_csrf_request();
    csrf_request
        .headers
        .insert("origin".to_string(), "https://evil-site.com".to_string());

    let violations = guard.enhanced_csrf_check(&csrf_request);
    println!("\n增强CSRF检查结果:");
    if violations.is_empty() {
        println!("  ✅ 未发现CSRF威胁");
    } else {
        println!("  ⚠️ 发现CSRF威胁:");
        for (i, violation) in violations.iter().enumerate() {
            println!(
                "    {}. {} [{}] {}",
                i + 1,
                match violation.severity {
                    SecuritySeverity::Low => "🔵",
                    SecuritySeverity::Medium => "🟡",
                    SecuritySeverity::High => "🟠",
                    SecuritySeverity::Critical => "🔴",
                },
                "CSRF攻击",
                violation.message
            );
        }
    }
}

fn print_violations(violations: &[security_lib::SecurityViolation]) {
    if violations.is_empty() {
        println!("  ✅ 未发现安全威胁");
        return;
    }

    println!("  ⚠️ 发现安全威胁:");
    for (i, violation) in violations.iter().enumerate() {
        let severity_symbol = match violation.severity {
            SecuritySeverity::Low => "🔵",
            SecuritySeverity::Medium => "🟡",
            SecuritySeverity::High => "🟠",
            SecuritySeverity::Critical => "🔴",
        };

        let rule_name = match violation.rule_type {
            SecurityRuleType::PathTraversal => "路径越权",
            SecurityRuleType::XssInjection => "XSS注入",
            SecurityRuleType::SqlInjection => "SQL注入",
            SecurityRuleType::CsrfProtection => "CSRF攻击",
            SecurityRuleType::InvalidHeader => "请求头异常",
            SecurityRuleType::FileUploadSecurity => "文件上传安全",
            SecurityRuleType::RateLimit => "频率限制",
        };

        println!(
            "  {}. {} [{}] {}",
            i + 1,
            severity_symbol,
            rule_name,
            violation.message
        );

        if let Some(field) = &violation.field {
            println!("     字段: {}", field);
        }

        if let Some(value) = &violation.value {
            let display_value = if value.len() > 50 {
                format!("{}...", &value[..50])
            } else {
                value.clone()
            };
            println!("     值: {}", display_value);
        }
    }
}
